package code.limiter;

import java.util.LinkedList;
import java.util.Queue;

// 这个实现看起来是更简单
public class SlidingWindow2 {
    private long capacity; // 窗口的总大小
    private long interval; // 窗口的时间大小，精确到毫秒 比如1000 代表窗口为1s
    private Queue<Long> timestamps; // 将请求的时间戳存储在队列中

    public SlidingWindow2(long _capacity, long _interval) {
        capacity = _capacity;
        interval = _interval;
        timestamps = new LinkedList<>();
    }

    public synchronized boolean Allow() {
        long now = System.currentTimeMillis();
        while (!timestamps.isEmpty() && (now - timestamps.peek() >= interval)) {
            timestamps.poll();
        }
        if (timestamps.size() >= capacity) {
            return false;
        }
        timestamps.add(now);
        return true;
    }

    public static void main(String[] args) throws Exception {
        SlidingWindow2 limiter = new SlidingWindow2(3, 1000); // 控制1秒钟3个请求
        for (int i=0; i<10; i++) {
            if (limiter.Allow()) {
                System.out.println(i+": OK");
            }else {
                System.out.println(i+": False");
            }
            Thread.sleep(200);
        }
    }
}
